﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

using SF.Utilities;

namespace SF.Export
{
    public static class EasyuiDatagridExport
    {
        private static string mergeExtensionProperty = "mergeInfos_";

        #region 导出easyui-datagrid时，对标题列集合、数据行集合处理的Api方法

        /// <summary>
        /// 处理标题列集合、数据行集合，返回完整规则的DataTable对象，并将解析所得的单元格合并规则以输出参数形式返回
        /// </summary>
        /// <param name="columns">标题列集合</param>
        /// <param name="data">数据行集合</param>
        /// <param name="rules">输出参数，根据标题列集合解析所得的单元格合并规则</param>
        /// <returns>完整规则的DataTable对象</returns>
        public static DataTable ParseColumnsAndRows(DataTable[] columns, DataTable data, out IEnumerable<MergerCellParamModel> rules)
        {
            #region 组建目标DataTable结构

            int columnsRowCount = columns.Length, columnsColCount = columns.Length > 0 ? columns[0].Rows.Count : 0;
            System.Data.DataTable dt = new System.Data.DataTable();
            for (int i = 0; i < columnsColCount; i++)
            {
                System.Data.DataRow mapRow = null;
                foreach (var item in columns)
                {
                    var tempRow = item.Rows[i];
                    if (tempRow["field"] != null && !string.IsNullOrWhiteSpace(tempRow["field"].ToString()))
                    {
                        mapRow = tempRow; break;
                    }
                }
                if (mapRow != null) { dt.Columns.Add(mapRow["field"].ToString(), typeof(string)); }
                else { dt.Columns.Add("列" + i, typeof(string)); }
            }

            #endregion

            Dictionary<string, int> fieldIndexs = new Dictionary<string, int>();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                fieldIndexs.TryAdd(dt.Columns[i].ColumnName, i);
            }

            #region 填充标题列数据

            foreach (var item in columns)
            {
                System.Data.DataRow newRow = dt.NewRow();
                for (int i = 0; i < columnsColCount; i++)
                {
                    newRow[i] = item.Rows[i]["title"];
                }
                dt.Rows.Add(newRow);
            }

            #endregion

            #region 标题列合并规则计算

            rules = new List<MergerCellParamModel>();
            Dictionary<string, MergerCellParamModel> dicRules = new Dictionary<string, MergerCellParamModel>();
            
            for (int k = 0; k < columns.Length; k++)
            {
                System.Data.DataTable itemFc = columns[k];
                for (int i = 0; i < itemFc.Rows.Count; i++)
                {
                    System.Data.DataRow itemRow = itemFc.Rows[i];
                    string field = itemRow["field"].ToString();
                    if (itemRow["colspan"].ToString() != "1")
                    {
                        string key = field + "_" + itemRow["title"].ToString();
                        MergerCellParamModel tempRule = null;
                        if (dicRules.TryGetValue(key, out tempRule))
                        {
                            tempRule.RowEndIndex = k;
                            tempRule.ColEndIndex = i;
                        }
                        else
                        {
                            tempRule = new MergerCellParamModel();
                            tempRule.RowStartIndex = k;
                            tempRule.ColStartIndex = i;
                            tempRule.Repeat = false;

                            dicRules.Add(key, tempRule);
                        }
                    }
                    if (itemRow["rowspan"].ToString() != "1")
                    {
                        string key = itemRow["field"].ToString() + "_" + itemRow["title"].ToString();
                        MergerCellParamModel tempRule = null;
                        if (dicRules.TryGetValue(key, out tempRule))
                        {
                            tempRule.RowEndIndex = k;
                            tempRule.ColEndIndex = i;
                        }
                        else
                        {
                            tempRule = new MergerCellParamModel();
                            tempRule.RowStartIndex = k;
                            tempRule.ColStartIndex = i;
                            tempRule.Repeat = false;

                            dicRules.Add(key, tempRule);
                        }
                    }
                }
            }

            rules = dicRules.Select(s => s.Value);

            #endregion

            #region 填充主体数据并获取主体数据合并信息

            List<MergeInfo> bodyMergeInfos = new List<MergeInfo>();
            List<MergerCellParamModel> bodyRules = new List<MergerCellParamModel>();
            for (int i = 0; i < data.Rows.Count; i++)
            {
                System.Data.DataRow newRow = dt.NewRow();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    string columnName = data.Columns[j].ColumnName; //Field名
                    if (columnName.StartsWith(mergeExtensionProperty) && columnName.Contains("_"))
                    {
                        string postfix = columnName.Split('_')[1];
                        Guid tempGuid;
                        bool isGuid = Guid.TryParseExact(postfix, "N", out tempGuid);
                        if (isGuid)
                        {
                            string mergeInfoString = data.Rows[i][j].ToString();//合并信息序列化字符串
                            if (!string.IsNullOrWhiteSpace(mergeInfoString))
                            {
                                //反序列化合并信息 DeserializeJsToDataTable
                                MergeInfo[] mergeArray = SF.Utilities.Serialization.DeserializeJsToArray<MergeInfo>(mergeInfoString);
                                //解析数据主体合并信息为合并规则
                                foreach (var item in mergeArray)
                                {
                                    MergerCellParamModel tempRule = new MergerCellParamModel();
                                    tempRule.RowStartIndex = item.index + columns.Length;
                                    tempRule.RowEndIndex = item.rowspan == 1 ? tempRule.RowStartIndex : (tempRule.RowStartIndex + (item.rowspan - 1));
                                    tempRule.ColStartIndex = fieldIndexs.GetValue(item.field);
                                    tempRule.ColEndIndex = item.colspan == 1 ? tempRule.ColStartIndex : (tempRule.ColStartIndex + (item.colspan - 1));
                                    bodyRules.Add(tempRule);
                                }
                            }
                            continue;
                        }
                    }
                    if (!dt.Columns.Contains(columnName)) { continue; }
                    object cellObject = data.Rows[i][j];//单元格内容

                    newRow[columnName] = cellObject;
                }
                dt.Rows.Add(newRow);
            }

            #endregion

            List<MergerCellParamModel> allRules = new List<MergerCellParamModel>();
            allRules.AddRange(rules);
            allRules.AddRange(bodyRules);

            rules = allRules.AsEnumerable();

            return dt;
        }

        #endregion

        /// <summary>
        /// 合并信息模型，用来解析datagrid数据体中的合并信息
        /// </summary>
        public class MergeInfo
        {
            /// <summary>
            /// 行索引
            /// </summary>
            public int index { get; set; }

            /// <summary>
            /// 字段
            /// </summary>
            public string field { get; set; }

            /// <summary>
            /// 占行数
            /// </summary>
            public int rowspan { get; set; }

            /// <summary>
            /// 占列数
            /// </summary>
            public int colspan { get; set; }
        }
    }
}
